package service

import (
	"encoding/json"
	"errors"
	"git.inedcn.com/ined/cmn"
	"github.com/mozillazg/go-pinyin"
	"rongyy/src/middlewares"
	"rongyy/src/models"
	"strconv"
	"strings"
)

type PatientRecruitmentService struct {
}

func (ps *PatientRecruitmentService) CreateIndication(req *models.IndicationModel) (*models.IndicationModel, error) {

	data, err := req.SelectByName(req.Name)
	if err != nil {
		return nil, err
	}
	if data != nil {
		return nil, errors.New("名称重复了")
	}
	err = req.Insert()
	if err != nil {
		return nil, err
	}
	return nil, nil
}

func (ps *PatientRecruitmentService) CreateDisease(req *models.DiseaseModel) (*models.DiseaseModel, error) {

	data, err := req.SelectByName(req.Name)
	if err != nil {
		return nil, err
	}
	if data != nil {
		return nil, errors.New("名称重复了")
	}
	err = req.Insert()
	if err != nil {
		return nil, err
	}
	return nil, nil
}

func (pc *PatientRecruitmentService) UpdateIndication(req *models.IndicationModel, id string) error {
	db, err := req.SelectById(id)
	if err != nil {
		return err
	}
	if db == nil {
		return errors.New("参数不对，请重新填写id")
	}
	db, err = req.SelectByName(req.Name)
	if err != nil {
		return err
	}
	int64, err := strconv.ParseInt(id, 10, 64)
	if db != nil && int64 != db.Id {
		return errors.New("名称错误，请重新填写")
	}
	err = req.UpdateData(req, id)
	if err != nil {
		return err
	}
	return nil
}

func (pc *PatientRecruitmentService) UpdateDisease(req *models.DiseaseModel, id string) error {
	err := req.UpdateData(req, id)
	if err != nil {
		return err
	}
	return nil
}

func (pc *PatientRecruitmentService) GetIndication() ([]models.IndicationModel, error) {
	model := &models.IndicationModel{}
	data, err := model.SelectAll()
	if err != nil {
		return nil, err
	}
	return data, nil
}

func (pc *PatientRecruitmentService) GetDisease() ([]models.DiseaseModel, error) {
	model := &models.DiseaseModel{}
	data, err := model.SelectAll()
	if err != nil {
		return nil, err
	}
	return data, nil
}

func (pc *PatientRecruitmentService) GetDataById(req *models.DiseaseModel, id string) (*models.DiseaseModel, error) {
	data, err := req.SelectById(id)
	if err != nil {
		return nil, err
	}
	return data, nil
}

func (pc *PatientRecruitmentService) GetDataByName(req *models.DiseaseModel, name string) (*models.DiseaseModel, error) {
	data, err := req.SelectByName(name)
	if err != nil {
		return nil, err
	}
	return data, nil
}

func (pc *PatientRecruitmentService) DeleteDisease(id string) error {
	model := &models.DiseaseModel{}
	err := model.DeleteDisease(id)
	if err != nil {
		return err
	}
	return nil
}

func (pc *PatientRecruitmentService) DeleteIndication(id string) error {
	model := &models.IndicationModel{}
	err := model.DeleteIndication(id)
	if err != nil {
		return err
	}
	return nil
}

func (ps *PatientRecruitmentService) CreateTargetSpot(req *models.TargetSpotModel) (*models.TargetSpotModel, error) {

	data, err := req.SelectByName(req.Name)
	if err != nil {
		return nil, err
	}
	if data != nil {
		return nil, errors.New("名称重复了")
	}
	err = req.Insert()
	if err != nil {
		return nil, err
	}
	return nil, nil
}
func (pc *PatientRecruitmentService) UpdateTargetSpot(req *models.TargetSpotModel, id string) error {
	db, err := req.SelectById(id)
	if err != nil {
		return err
	}
	if db == nil {
		return errors.New("参数不对，请重新填写id")
	}
	db, err = req.SelectByName(req.Name)
	if err != nil {
		return err
	}
	int64, err := strconv.ParseInt(id, 10, 64)
	if db != nil && int64 != db.Id {
		return errors.New("名称错误，请重新填写")
	}
	err = req.UpdateData(req, id)
	if err != nil {
		return err
	}
	return nil
}

func (pc *PatientRecruitmentService) DeleteTargetSpot(id string) error {
	model := &models.TargetSpotModel{}
	err := model.DeleteTargetSpot(id)
	if err != nil {
		return err
	}
	return nil
}

func (pc *PatientRecruitmentService) GetTargetSpot() ([]models.TargetSpotModel, error) {
	model := &models.TargetSpotModel{}
	data, err := model.SelectAll()
	if err != nil {
		return nil, err
	}
	return data, nil
}

func (ps *PatientRecruitmentService) CreatePathology(req *models.PathologyModel) (*models.PathologyModel, error) {

	data, err := req.SelectByName(req.Name)
	if err != nil {
		return nil, err
	}
	if data != nil {
		return nil, errors.New("名称重复了")
	}
	err = req.Insert()
	if err != nil {
		return nil, err
	}
	return nil, nil
}
func (pc *PatientRecruitmentService) UpdatePathology(req *models.PathologyModel, id string) error {
	db, err := req.SelectById(id)
	if err != nil {
		return err
	}
	if db == nil {
		return errors.New("参数不对，请重新填写id")
	}
	db, err = req.SelectByName(req.Name)
	if err != nil {
		return err
	}
	int64, err := strconv.ParseInt(id, 10, 64)
	if db != nil && int64 != db.Id {
		return errors.New("名称错误，请重新填写")
	}
	err = req.UpdateData(req, id)
	if err != nil {
		return err
	}
	return nil
}

func (pc *PatientRecruitmentService) DeletePathology(id string) error {
	model := &models.PathologyModel{}
	err := model.DeletePathology(id)
	if err != nil {
		return err
	}
	return nil
}

func (pc *PatientRecruitmentService) GetPathology() ([]models.PathologyModel, error) {
	model := &models.PathologyModel{}
	data, err := model.SelectAll()
	if err != nil {
		return nil, err
	}
	return data, nil
}

func (pc *PatientRecruitmentService) CreateRecruitment(req *models.RecruitmentModel) error {
	//if req.Name == "" {
	//	return errors.New("名称不能为空")
	//}
	//if req.Num == "" {
	//	return errors.New("项目编号不能空")
	//}
	//if req.Drug == "" {
	//	return errors.New("实验药物不能为空")
	//}
	//if len(req.IndicationIds) == 0 {
	//	return errors.New("适应症不能为空")
	//}
	//if len(req.DiseaseIds) == 0 {
	//	return errors.New("病种不能为空")
	//}
	//if len(req.PathologyIds) == 0 {
	//	return errors.New("病理不能为空")
	//}
	//if len(req.StageIds) == 0 {
	//	return errors.New("分期不能为空")
	//}
	//if req.InclusionCriteria == "" {
	//	return errors.New("入选标准不能为空")
	//}
	//if req.ExclusionCriteria == "" {
	//	return errors.New("排除标准不能为空")
	//}

	db, err := req.SelectByName(req.Name)
	if err != nil {
		return err
	}
	if db != nil {
		return errors.New("名称已存在请，重新入名称")
	}
	db, err = req.SelectByNum(req.Name)
	if err != nil {
		return err
	}
	if db != nil {
		return errors.New("项目编号已存在请，重新入编号")
	}
	err = req.Insert()
	if err != nil {
		return err
	}
	return nil
}

func (pc *PatientRecruitmentService) UpdateRecruitment(req *models.RecruitmentModel, id string) error {
	dbData, err := req.SelectById(id)
	if err != nil {
		return err
	}
	if dbData == nil {
		return errors.New("参数错误")
	}
	//if req.InclusionCriteria == "" {
	//	return errors.New("入选标准不能为空")
	//}
	//if req.ExclusionCriteria == "" {
	//	return errors.New("排除标准不能为空")
	//}
	//if req.Name == "" {
	//	return errors.New("名称不能为空")
	//}
	//if req.Num == "" {
	//	return errors.New("项目编号不能空")
	//}
	//if req.Drug == "" {
	//	return errors.New("实验药物不能为空")
	//}
	//if len(req.IndicationIds) == 0 {
	//	return errors.New("适应症不能为空")
	//}
	//if len(req.DiseaseIds) == 0 {
	//	return errors.New("病种不能为空")
	//}
	//if len(req.PathologyIds) == 0 {
	//	return errors.New("病理不能为空")
	//}
	//if len(req.StageIds) == 0 {
	//	return errors.New("分期不能为空")
	//}
	int64, err := strconv.ParseInt(id, 10, 64)
	if err != nil {
		return err
	}
	db, err := req.SelectByName(req.Name)
	if err != nil {
		return err
	}
	if db != nil && db.Id != int64 {
		return errors.New("名称已存在,请重新入名称")
	}
	db, err = req.SelectByNum(req.Name)
	if err != nil {
		return err
	}
	if db != nil && db.Id != int64 {
		return errors.New("项目编号已存在,请重新入编号")
	}

	req.Id = dbData.Id
	err = dbData.Update(req)
	if err != nil {
		return err
	}
	return nil
}

func (pc *PatientRecruitmentService) RecruitmentStatus(req *models.RecruitmentModel, id string) error {
	dbData, err := req.SelectById(id)
	if err != nil {
		return err
	}
	if dbData == nil {
		return errors.New("参数错误")
	}
	req.Id = dbData.Id
	err = dbData.UpdateStatus(req)
	if err != nil {
		return err
	}
	return nil
}

func (pc *PatientRecruitmentService) RecruitmentMoreStatus(req *models.RecruitmentModel) error {
	for _, id := range req.Ids {
		dbData, err := req.SelectById(strconv.FormatInt(id, 10))
		if err != nil {
			return err
		}
		if dbData == nil {
			return errors.New("参数错误")
		}
		req.Id = dbData.Id
		err = dbData.UpdateStatus(req)
		if err != nil {
			return err
		}
	}

	return nil
}

func (pc *PatientRecruitmentService) RecruitmentDelete(id string) error {
	model := &models.RecruitmentModel{}
	dbData, err := model.SelectById(id)
	if err != nil {
		return err
	}
	if dbData == nil {
		return errors.New("参数错误")
	}
	if dbData.Status == "招募中" {
		return errors.New("招募中不能删除")
	}
	err = dbData.Delete(id)
	if err != nil {
		return err
	}
	modelApp := &models.ApplicationModel{}
	err = modelApp.DeleteByRId(id)
	if err != nil {
		return err
	}
	return nil
}

func (pc *PatientRecruitmentService) GetRecruitment(stage string, status string, doctor string, drug string,
	name string, pathologies string, disease string, key string, party string) ([]models.RecruitmentModel, error) {
	model := &models.RecruitmentModel{}
	imodel := &models.IndicationModel{}
	iData, err := imodel.SelectByNameAll(key)
	if err != nil {
		return nil, err
	}
	data, err := model.SelectData(status, stage, doctor, drug, name, pathologies, disease, key, iData, party)
	if err != nil {
		return nil, err
	}
	var DiseasesStr = ""
	var IndicationsStr = ""
	var PathologysStr = ""
	var StagesStr = ""
	var TreatmentLinesStr = ""
	for index, v := range data {
		pathologyIds := strings.Split(v.PathologyIds, ",")
		pathologies := make([]models.PathologyModel, len(pathologyIds))
		pathologyModel := models.PathologyModel{}
		for i, pId := range pathologyIds {
			p, _ := pathologyModel.SelectById(pId)
			if p != nil {
				pathologies[i] = *p
				PathologysStr += p.Name + ","
			}
		}
		for i := 0; i < len(pathologies); i++ {
			if pathologies[i] == (models.PathologyModel{}) {
				pathologies = append(pathologies[:i], pathologies[i+1:]...)
				i--
			}
		}
		data[index].Pathologies = pathologies
		data[index].PathologysStr = strings.TrimRight(PathologysStr, ",")

		diseaseIds := strings.Split(v.DiseaseIds, ",")
		diseases := make([]models.DiseaseModel, len(diseaseIds))
		diseaseModel := models.DiseaseModel{}
		for i, pId := range diseaseIds {
			p, _ := diseaseModel.SelectById(pId)
			if p != nil {
				diseases[i] = *p
				DiseasesStr += p.Name + ","
			}
		}

		for i := 0; i < len(diseases); i++ {
			if diseases[i] == (models.DiseaseModel{}) {
				diseases = append(diseases[:i], diseases[i+1:]...)
				i--
			}
		}

		data[index].Diseases = diseases
		data[index].DiseasesStr = strings.TrimRight(DiseasesStr, ",")
		targetSpotIds := strings.Split(v.TargetSpotIds, ",")
		targetSpots := make([]models.TargetSpotModel, len(targetSpotIds))
		targetSpotModel := models.TargetSpotModel{}
		for i, id := range targetSpotIds {
			p, _ := targetSpotModel.SelectById(id)
			if p != nil {
				targetSpots[i] = *p
			}
		}

		for i := 0; i < len(targetSpots); i++ {
			if targetSpots[i] == (models.TargetSpotModel{}) {
				targetSpots = append(targetSpots[:i], targetSpots[i+1:]...)
				i--
			}
		}

		data[index].TargetSpots = targetSpots
		indicationIds := strings.Split(v.IndicationIds, ",")
		indications := make([]models.IndicationModel, len(indicationIds))
		indicationModel := models.IndicationModel{}
		for i, pId := range indicationIds {
			p, _ := indicationModel.SelectById(pId)
			if p != nil {
				indications[i] = *p
				IndicationsStr += p.Name + ","
			}
		}

		for i := 0; i < len(indications); i++ {
			if indications[i] == (models.IndicationModel{}) {
				indications = append(indications[:i], indications[i+1:]...)
				i--
			}
		}
		data[index].Indications = indications
		data[index].IndicationsStr = strings.TrimRight(IndicationsStr, ",")

		stageIds := strings.Split(v.StageIds, ",")
		stages := make([]models.StageModel, len(stageIds))
		stageModel := models.StageModel{}
		for i, pId := range stageIds {
			p, _ := stageModel.SelectById(pId)
			if p != nil {
				stages[i] = *p
				StagesStr += p.Name + ","
			}
		}
		for i := 0; i < len(stages); i++ {
			if stages[i] == (models.StageModel{}) {
				stages = append(stages[:i], stages[i+1:]...)
				i--
			}
		}
		data[index].Stages = stages
		data[index].StagesStr = strings.TrimRight(StagesStr, ",")

		treatmentLineIds := strings.Split(v.TreatmentLineIds, ",")
		treatmentLineList := make([]models.TreatmentLineModel, len(treatmentLineIds))
		treatmentLineModel := models.TreatmentLineModel{}
		for i, pId := range treatmentLineIds {
			p, _ := treatmentLineModel.SelectById(pId)
			if p != nil {
				treatmentLineList[i] = *p
				TreatmentLinesStr += p.Name + ","
			}
		}
		for i := 0; i < len(treatmentLineList); i++ {
			if treatmentLineList[i] == (models.TreatmentLineModel{}) {
				treatmentLineList = append(treatmentLineList[:i], treatmentLineList[i+1:]...)
				i--
			}
		}
		data[index].TreatmentLineList = treatmentLineList
		data[index].TreatmentLinesStr = strings.TrimRight(TreatmentLinesStr, ",")
	}

	return data, nil
}

func (pc *PatientRecruitmentService) CreateApplication(req *models.ApplicationModel) error {
	if req.Name == "" {
		return errors.New("姓名不能为空")
	}

	if req.Rid == 0 {
		return errors.New("招募不能为空")
	}
	re := models.RecruitmentModel{}
	reData, err := re.SelectById(strconv.FormatInt(req.Rid, 10))
	if reData == nil {
		return errors.New("招募信息错误")
	}
	req.RecruitmentName = reData.Name
	if reData.Status != "招募中" {
		return errors.New(reData.Status)
	}
	if req.ReadStatus == "" {
		req.ReadStatus = "未查看"
	}

	if req.Sex == "" {
		return errors.New("性别不能为空")
	}

	if req.Phone == "" {
		return errors.New("手机不能为空")
	}
	if req.Birthday == (cmn.JsonDate{}) {
		return errors.New("出生日期不能为空")
	}
	if req.Contacted == "" {
		return errors.New("是否已联系项目负责医生或已挂号不能为空")
	}

	db, err := req.SelectByNameAndRid(req.Name, req.Rid)
	if err != nil {
		return err
	}
	if db != nil {
		return errors.New("已申请招募，不用在重复申请")
	}

	err = req.Insert()
	if err != nil {
		return err
	}
	return nil
}

func (pc *PatientRecruitmentService) GetApplication(unionId string, indexInt int, sizeInt int,
	name string, from string, to string, disease string, key string, num string,
	status string) ([]models.ApplicationModel, int64, error) {
	model := models.ApplicationModel{}
	rModel := models.RecruitmentModel{}
	dataDb, err := rModel.SelectBySchemeNum(num)
	if err != nil {
		return nil, 0, err
	}
	data, total, err := model.SelectData(unionId, indexInt, sizeInt, name, from, to, disease, key, dataDb, status)

	for index, v := range data {
		diseaseIds := strings.Split(v.Disease, ",")
		diseases := make([]models.DiseaseModel, len(diseaseIds))
		diseaseModel := models.DiseaseModel{}
		for i, pId := range diseaseIds {
			p, _ := diseaseModel.SelectById(pId)
			if p != nil {
				diseases[i] = *p
			}
		}

		for i := 0; i < len(diseases); i++ {
			if diseases[i] == (models.DiseaseModel{}) {
				diseases = append(diseases[:i], diseases[i+1:]...)
				i--
			}
		}

		data[index].DiseaseList = diseases

		model := &models.RecruitmentModel{}
		dbData, err := model.SelectById(strconv.FormatInt(v.Rid, 10))
		if err != nil {
			return nil, 0, err
		}
		data[index].Recruitment = dbData
	}
	if err != nil {
		return nil, 0, err
	}
	return data, total, nil
}

func (pc *PatientRecruitmentService) ApplicationExport(patientId string, name string, from string, to string,
	disease string, key string, num string, status string) []models.ApplicationModel {
	model := models.ApplicationModel{}
	rModel := models.RecruitmentModel{}
	dataDb, err := rModel.SelectBySchemeNum(num)
	if err != nil {
		return nil
	}
	data, _, err := model.SelectData(patientId, 0, 100000, name, from, to, disease, key, dataDb, status)
	for index, v := range data {
		diseaseIds := strings.Split(v.Disease, ",")
		diseaseModel := models.DiseaseModel{}
		var diseaseStr = ""
		for _, pId := range diseaseIds {
			p, _ := diseaseModel.SelectById(pId)
			if p != nil {
				diseaseStr += p.Name
			}
		}

		data[index].DiseaseStr = diseaseStr

		model := &models.RecruitmentModel{}
		dbData, err := model.SelectById(strconv.FormatInt(v.Rid, 10))
		if err != nil {
			return nil
		}
		data[index].Recruitment = dbData
	}

	if err != nil {
		return nil
	}
	return data
}

func (pc *PatientRecruitmentService) ReadApplication(req *models.ApplicationModel) error {
	model := models.ApplicationModel{}
	data, err := model.SelectById(req.Id)

	if data == nil {
		return errors.New("参数不能为空")
	}
	if err != nil {
		return err
	}
	data.ReadStatus = req.ReadStatus
	data.ReadUserName = req.ReadUserName
	data.ReadUserId = req.ReadUserId
	err = model.Update(data)
	if err != nil {
		return err
	}
	return nil
}
func (pc *PatientRecruitmentService) MoreReadApplication(req *models.ApplicationModel) error {
	for _, id := range req.Ids {
		req.Id = id
		model := models.ApplicationModel{}
		data, err := model.SelectById(req.Id)

		if data == nil {
			return errors.New("参数不能为空")
		}
		if err != nil {
			return err
		}
		data.ReadStatus = req.ReadStatus
		data.ReadUserName = req.ReadUserName
		data.ReadUserId = req.ReadUserId
		err = model.Update(data)
		if err != nil {
			return err
		}
	}

	return nil
}

func (pc *PatientRecruitmentService) CreateRecruitmentExport(rows [][]string) error {

	// 循环刚刚获取到的表中的值
	for key, row := range rows {
		// 去掉标题行
		if key > 1 {
			req := &models.RecruitmentModel{}
			req.Name = row[0]

			dbData, err := req.SelectByName(req.Name)
			if dbData != nil {
				continue
			}
			req.Num = row[1]
			req.SchemeNum = row[2]
			req.DeclaringParty = row[3]
			req.Drug = row[4]
			//req.StopTime = row[0]
			//req.Stage = row[9]
			//分期
			var stageStr = row[9]
			stageArr := strings.Split(stageStr, ",")
			for _, v := range stageArr {
				stageModel := &models.StageModel{}
				data, err := stageModel.SelectByName(v)
				if err != nil {
					continue
				}
				if data == nil {
					stageModel.Name = v
					stageModel.Insert()
					req.StageIds += "," + strconv.FormatInt(stageModel.Id, 10)
				} else {
					req.StageIds += "," + strconv.FormatInt(data.Id, 10)
				}

			}
			req.StageIds = strings.TrimPrefix(req.StageIds, ",")

			//req.TreatmentPlan = row[0]
			req.InclusionCriteria = row[12]
			req.ExclusionCriteria = row[13]
			//req.TreatmentLines = row[10]
			//治疗线数
			var treatmentLineStr = row[10]
			treatmentLineArr := strings.Split(treatmentLineStr, ",")
			for _, v := range treatmentLineArr {
				treatmentLineModel := &models.TreatmentLineModel{}
				data, err := treatmentLineModel.SelectByName(v)
				if err != nil {
					continue
				}
				if data == nil {
					treatmentLineModel.Name = v
					treatmentLineModel.Insert()
					req.TreatmentLineIds += "," + strconv.FormatInt(treatmentLineModel.Id, 10)
				} else {
					req.TreatmentLineIds += "," + strconv.FormatInt(data.Id, 10)
				}

			}
			req.TreatmentLineIds = strings.TrimPrefix(req.TreatmentLineIds, ",")
			if len(rows) > 14 {
				req.Contacts = row[15]
				req.ContactsPhone = row[16]
			}
			req.MasterDoctor = row[11]
			//病种
			var diseaseStr = row[6]
			diseaseArr := strings.Split(diseaseStr, ",")
			for _, v := range diseaseArr {
				diseaseModel := &models.DiseaseModel{}
				data, err := diseaseModel.SelectByName(v)
				if err != nil {
					continue
				}
				if data == nil {
					pinyinValue := pinyin.NewArgs()
					value := pinyin.LazyPinyin(v, pinyinValue)
					middlewares.Logger.Println("createDisease  pinyin -", value)
					pinyinZh := strings.Join(value, " ")
					diseaseModel.NamePinyin = pinyinZh
					if len(pinyinZh) > 0 {
						diseaseModel.NameHead = string(pinyinZh[0])
					}
					diseaseModel.Name = v
					diseaseModel.Insert()
					req.DiseaseIds += "," + strconv.FormatInt(diseaseModel.Id, 10)
				} else {
					req.DiseaseIds += "," + strconv.FormatInt(data.Id, 10)
				}

			}
			req.DiseaseIds = strings.TrimPrefix(req.DiseaseIds, ",")

			//适应症
			var indicationStr = row[5]
			indicationArr := strings.Split(indicationStr, ",")
			for _, v := range indicationArr {
				indicationModel := &models.IndicationModel{}
				data, err := indicationModel.SelectByName(v)
				if err != nil {
					continue
				}
				if data == nil {
					indicationModel.Name = v
					indicationModel.Insert()
					req.IndicationIds += "," + strconv.FormatInt(indicationModel.Id, 10)
				} else {
					req.IndicationIds += "," + strconv.FormatInt(data.Id, 10)
				}

			}
			req.IndicationIds = strings.TrimPrefix(req.IndicationIds, ",")

			//靶点

			var targetSpotStr = row[8]
			targetSpotArr := strings.Split(targetSpotStr, ",")
			for _, v := range targetSpotArr {
				targetSpotModel := &models.TargetSpotModel{}
				data, err := targetSpotModel.SelectByName(v)
				if err != nil {
					continue
				}
				if data == nil {
					targetSpotModel.Name = v
					targetSpotModel.Insert()
					req.TargetSpotIds += "," + strconv.FormatInt(targetSpotModel.Id, 10)
				} else {
					req.TargetSpotIds += "," + strconv.FormatInt(data.Id, 10)
				}

			}
			req.TargetSpotIds = strings.TrimPrefix(req.TargetSpotIds, ",")

			//病理
			var pathologyStr = row[7]
			pathologyArr := strings.Split(pathologyStr, ",")
			for _, v := range pathologyArr {
				pathologyModel := &models.PathologyModel{}
				data, err := pathologyModel.SelectByName(v)
				if err != nil {
					continue
				}
				if data == nil {
					pinyinValue := pinyin.NewArgs()
					value := pinyin.LazyPinyin(v, pinyinValue)
					middlewares.Logger.Println("createDisease  pinyin -", value)
					pinyinZh := strings.Join(value, " ")
					pathologyModel.NamePinyin = pinyinZh
					if len(pinyinZh) > 0 {
						pathologyModel.NameHead = string(pinyinZh[0])
					}
					pathologyModel.Name = v
					pathologyModel.Insert()
					req.PathologyIds += "," + strconv.FormatInt(pathologyModel.Id, 10)
				} else {
					req.PathologyIds += "," + strconv.FormatInt(data.Id, 10)
				}

			}
			req.PathologyIds = strings.TrimPrefix(req.PathologyIds, ",")

			//团队

			var datas []interface{}
			ResearchTeamsArr := strings.Split(row[14], ",")
			for _, v := range ResearchTeamsArr {
				data := strings.Split(v, "-")
				datas = append(datas, TeamInfo{
					Name:       data[0],
					Department: data[1],
				})
			}

			data, err := json.Marshal(&datas)
			req.ResearchTeams = string(data)
			req.Status = "招募中"
			err = pc.CreateRecruitment(req)
			if err != nil {
				continue
			}
		}
	}
	return nil
}

func (pc *PatientRecruitmentService) CreateRecruitmentExportV2(rows [][]string) error {

	// 循环刚刚获取到的表中的值
	for key, row := range rows {
		// 去掉标题行
		if key > 0 {
			req := &models.RecruitmentModel{}
			req.Name = row[0]

			dbData, err := req.SelectByName(req.Name)
			if dbData != nil {
				continue
			}
			req.Num = row[1]
			req.SchemeNum = row[2]
			req.Drug = row[3]
			//病种
			var diseaseStr = row[4]
			diseaseArr := strings.Split(diseaseStr, ",")
			for _, v := range diseaseArr {
				diseaseModel := &models.DiseaseModel{}
				data, err := diseaseModel.SelectByName(v)
				if err != nil {
					continue
				}
				if data == nil {
					pinyinValue := pinyin.NewArgs()
					value := pinyin.LazyPinyin(v, pinyinValue)
					middlewares.Logger.Println("createDisease  pinyin -", value)
					pinyinZh := strings.Join(value, " ")
					diseaseModel.NamePinyin = pinyinZh
					if len(pinyinZh) > 0 {
						diseaseModel.NameHead = string(pinyinZh[0])
					}
					diseaseModel.Name = v
					diseaseModel.Insert()
					req.DiseaseIds += "," + strconv.FormatInt(diseaseModel.Id, 10)
				} else {
					req.DiseaseIds += "," + strconv.FormatInt(data.Id, 10)
				}

			}
			req.DiseaseIds = strings.TrimPrefix(req.DiseaseIds, ",")

			//适应症
			var indicationStr = row[5]
			indicationArr := strings.Split(indicationStr, ",")
			for _, v := range indicationArr {
				indicationModel := &models.IndicationModel{}
				data, err := indicationModel.SelectByName(v)
				if err != nil {
					continue
				}
				if data == nil {
					indicationModel.Name = v
					indicationModel.Insert()
					req.IndicationIds += "," + strconv.FormatInt(indicationModel.Id, 10)
				} else {
					req.IndicationIds += "," + strconv.FormatInt(data.Id, 10)
				}

			}
			req.IndicationIds = strings.TrimPrefix(req.IndicationIds, ",")

			//病理
			var pathologyStr = row[6]
			pathologyArr := strings.Split(pathologyStr, ",")
			for _, v := range pathologyArr {
				pathologyModel := &models.PathologyModel{}
				data, err := pathologyModel.SelectByName(v)
				if err != nil {
					continue
				}
				if data == nil {
					pinyinValue := pinyin.NewArgs()
					value := pinyin.LazyPinyin(v, pinyinValue)
					middlewares.Logger.Println("createDisease  pinyin -", value)
					pinyinZh := strings.Join(value, " ")
					pathologyModel.NamePinyin = pinyinZh
					if len(pinyinZh) > 0 {
						pathologyModel.NameHead = string(pinyinZh[0])
					}
					pathologyModel.Name = v
					pathologyModel.Insert()
					req.PathologyIds += "," + strconv.FormatInt(pathologyModel.Id, 10)
				} else {
					req.PathologyIds += "," + strconv.FormatInt(data.Id, 10)
				}

			}
			req.PathologyIds = strings.TrimPrefix(req.PathologyIds, ",")

			//分期
			var stageStr = row[7]
			stageArr := strings.Split(stageStr, ",")
			for _, v := range stageArr {
				stageModel := &models.StageModel{}
				data, err := stageModel.SelectByName(v)
				if err != nil {
					continue
				}
				if data == nil {
					stageModel.Name = v
					stageModel.Insert()
					req.StageIds += "," + strconv.FormatInt(stageModel.Id, 10)
				} else {
					req.StageIds += "," + strconv.FormatInt(data.Id, 10)
				}

			}
			req.StageIds = strings.TrimPrefix(req.StageIds, ",")

			//治疗线数
			var treatmentLineStr = row[8]
			treatmentLineArr := strings.Split(treatmentLineStr, ",")
			for _, v := range treatmentLineArr {
				treatmentLineModel := &models.TreatmentLineModel{}
				data, err := treatmentLineModel.SelectByName(v)
				if err != nil {
					continue
				}
				if data == nil {
					treatmentLineModel.Name = v
					treatmentLineModel.Insert()
					req.TreatmentLineIds += "," + strconv.FormatInt(treatmentLineModel.Id, 10)
				} else {
					req.TreatmentLineIds += "," + strconv.FormatInt(data.Id, 10)
				}

			}
			req.TreatmentLineIds = strings.TrimPrefix(req.TreatmentLineIds, ",")

			//req.TreatmentPlan = row[0]
			req.InclusionCriteria = row[9]
			req.ExclusionCriteria = row[10]

			//req.TreatmentLines = row[10]
			req.MasterDoctor = row[14]
			if len(row) > 14 {
				req.Contacts = row[15]
				req.ContactsPhone = row[16]
			}

			req.Status = "招募中"
			err = pc.CreateRecruitment(req)
			if err != nil {
				continue
			}
		}
	}
	return nil
}
func (pc *PatientRecruitmentService) GetStage() ([]models.StageModel, error) {
	model := &models.StageModel{}
	data, err := model.SelectAll()
	if err != nil {
		return nil, err
	}
	return data, nil
}

func (ps *PatientRecruitmentService) CreateStage(req *models.StageModel) (*models.StageModel, error) {

	data, err := req.SelectByName(req.Name)
	if err != nil {
		return nil, err
	}
	if data != nil {
		return nil, errors.New("名称重复了")
	}
	err = req.Insert()
	if err != nil {
		return nil, err
	}
	return nil, nil
}

func (pc *PatientRecruitmentService) UpdateStage(req *models.StageModel, id string) error {
	db, err := req.SelectById(id)
	if err != nil {
		return err
	}
	if db == nil {
		return errors.New("参数不对，请重新填写id")
	}
	db, err = req.SelectByName(req.Name)
	if err != nil {
		return err
	}
	int64, err := strconv.ParseInt(id, 10, 64)
	if db != nil && int64 != db.Id {
		return errors.New("名称错误，请重新填写")
	}
	err = req.UpdateData(req, id)
	if err != nil {
		return err
	}
	return nil
}

func (pc *PatientRecruitmentService) DeleteStage(id string) error {
	model := &models.StageModel{}
	err := model.DeleteStage(id)
	if err != nil {
		return err
	}
	return nil
}

func (pc *PatientRecruitmentService) GetTreatmentLine() ([]models.TreatmentLineModel, error) {
	model := &models.TreatmentLineModel{}
	data, err := model.SelectAll()
	if err != nil {
		return nil, err
	}
	return data, nil
}

func (ps *PatientRecruitmentService) CreateTreatmentLine(req *models.TreatmentLineModel) (*models.TreatmentLineModel, error) {

	data, err := req.SelectByName(req.Name)
	if err != nil {
		return nil, err
	}
	if data != nil {
		return nil, errors.New("名称重复了")
	}
	err = req.Insert()
	if err != nil {
		return nil, err
	}
	return nil, nil
}

func (pc *PatientRecruitmentService) UpdateTreatmentLine(req *models.TreatmentLineModel, id string) error {
	db, err := req.SelectById(id)
	if err != nil {
		return err
	}
	if db == nil {
		return errors.New("参数不对，请重新填写id")
	}
	db, err = req.SelectByName(req.Name)
	if err != nil {
		return err
	}
	int64, err := strconv.ParseInt(id, 10, 64)
	if db != nil && int64 != db.Id {
		return errors.New("名称错误，请重新填写")
	}
	err = req.UpdateData(req, id)
	if err != nil {
		return err
	}
	return nil
}

func (pc *PatientRecruitmentService) DeleteTreatmentLine(id string) error {
	model := &models.TreatmentLineModel{}
	err := model.DeleteTreatmentLine(id)
	if err != nil {
		return err
	}
	return nil
}

func (pc *PatientRecruitmentService) SaveParamsManger(req *models.ParamsMangerModel) error {
	db, err := req.SelectByType(req.Name)
	if err != nil {
		return err
	}
	if db == nil {
		err = req.Insert()
		if err != nil {
			return err
		}
	} else {
		db.NotRequired = req.NotRequired
		db.Required = req.Required
		req.UpdateData(db, strconv.FormatInt(db.Id, 10))
	}
	return nil
}

func (pc *PatientRecruitmentService) UpdateParamsManger(req *models.ParamsMangerModel) error {
	db, err := req.SelectById(strconv.FormatInt(req.Id, 10))
	if err != nil {
		return err
	}
	if db == nil {
		return errors.New("参数不对，请重新填写id")
	} else {
		db.NotRequired = req.NotRequired
		db.Required = req.Required
		req.UpdateData(db, strconv.FormatInt(db.Id, 10))
	}
	return nil
}

func (pc *PatientRecruitmentService) GetParamsManger(name string) (*models.ParamsMangerModel, error) {
	doc := &models.ParamsMangerModel{}
	data, err := doc.SelectByType(name)
	if err != nil {
		return nil, err
	}

	return data, nil
}

type TeamInfo struct {
	Name       string
	Department string
}

func (pc *PatientRecruitmentService) RecruitmentUpdateStatus() error {
	model := &models.RecruitmentModel{}
	err := model.UpdateAllStatus()
	return err
}
